/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alipay.sofa.dashboard.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Provide an instance of the ZooKeeper client in the Spring application environment
 *
 * @author: guolei.sgl (guolei.sgl@antfin.com) 2019/2/15 11:59 AM
 * @since:
 **/
@Component
public class ZkCommandClient implements InitializingBean {

    private CuratorFramework curatorClient;

    @Value("${com.alipay.sofa.dashboard.zookeeper.address:localhost:2181}")
    private String           connectString;

    @Value("${com.alipay.sofa.dashboard.zookeeper.baseSleepTimeMs:1000}")
    private int              baseSleepTimeMs;

    @Value("${com.alipay.sofa.dashboard.zookeeper.maxRetries:3}")
    private int              maxRetries;

    @Value("${com.alipay.sofa.dashboard.zookeeper.sessionTimeoutMs:6000}")
    private int              sessionTimeoutMs;

    @Value("${com.alipay.sofa.dashboard.zookeeper.connectionTimeoutMs:6000}")
    private int              connectionTimeoutMs;

    @Override
    public void afterPropertiesSet() throws Exception {
        // custom policy
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
        // to build curatorClient
        curatorClient = CuratorFrameworkFactory.builder().connectString(connectString)
            .sessionTimeoutMs(sessionTimeoutMs).connectionTimeoutMs(connectionTimeoutMs)
            .retryPolicy(retryPolicy).build();
        curatorClient.start();
    }

    public CuratorFramework getCuratorClient() {
        return curatorClient;
    }
}
